import socket
import threading
import time

global server_on


def create_server_socket():
    """
    创建服务器Socket
    :return: server_socket(IPV4, TCP)
    """
    # IPV4 TCP
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = "127.0.0.1"
    port = 666
    server_socket.bind((host, port))
    # 设置超时时间
    server_socket.settimeout(10)
    print(f"Socket created, timeout: {server_socket.gettimeout()}")
    # 设置最大
    server_socket.listen(1)
    return server_socket


def server():
    global server_on
    server_socket = create_server_socket()
    while server_on:
        try:
            client_socket, addr = server_socket.accept()
        except socket.timeout:
            print("server timeout!")
            continue
        print(f"connect from {addr}")
        msg = "wdnmd CBJ!!!"
        client_socket.send(msg.encode("utf-8"))
        client_socket.close()
        print("send OK!")
        server_on = False


def client():
    """
    客户端, 只接收一次
    """
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = "127.0.0.1"
    port = 666
    try:
        client_socket.connect((host, port))
        recv_bytes = client_socket.recv(1024)
        print(recv_bytes.decode("utf-8"))
    except ConnectionError as e:
        print("ConnectionError at client")
        print(e.args)


def test_break_flag():
    global server_on
    server_on = False
    time.sleep(15)
    client()


if __name__ == '__main__':
    server_on = True
    t_server = threading.Thread(target=server)
    t_server.start()
    # t_client = threading.Thread(target=client)
    # t_client.start()
    t_breakTest = threading.Thread(target=test_break_flag)
    t_breakTest.start()

    t_server.join()
    # t_client.join()
    t_breakTest.join()
